﻿/*!
 * Copyright (c), 上海沃恩信息科技有限公司.
 * All rights reserved.
 * Licensed under BSD (https://www.pittypat.work/bsd.html).
 */

using System;
using System.IO;

namespace Pittypat.Web
{
    /// <summary>
    /// 表示发送给客户端的异步进度消息。
    /// </summary>
    /// <remarks>
    /// <see cref="IAsyncProgress"/> 向客户端发送的进度信息使用该消息发送。
    /// </remarks>
    sealed class ProgressMessage : ValueMessage
    {
        private float percent;
        private string message;

        /// <summary>
        /// 使用进度百分比、进度消息和值初始化 <see cref="ProgressMessage"/> 类的新实例。
        /// </summary>
        /// <param name="percent">进度百分比，介于 0 和 100 之间。如果小于 0，使用 0，如果大于 100，使用 100。</param>
        /// <param name="message">进度消息。</param>
        /// <param name="value">值。</param>
        internal ProgressMessage(float percent, string message, IJson value)
            : base(value)
        {
            this.percent = Math.Max(Math.Min(percent, 100f), 0f);
            this.message = message ?? "";
        }

        /// <summary>
        /// 获取当前进度的百分比。
        /// </summary>
        internal float Percent
        {
            get
            {
                return this.percent;
            }
        }

        /// <summary>
        /// 获取当前进度消息。
        /// </summary>
        internal string Message
        {
            get
            {
                return this.message;
            }
        }
        
        /// <summary>
        /// 将当前对象作为 JSON 字符串写入指定的文本流。
        /// </summary>
        /// <param name="writer">目标文本流。</param>
        /// <exception cref="ArgumentNullException">writer 是 null。</exception>
        public override void Write(TextWriter writer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }

            writer.Write("{{\"type\":\"progress\",\"percent\":{0:G},\"message\":\"{1}\",\"value\":",
                this.percent, Json.Escape(this.message));

            if (this.Value == null)
            {
                writer.Write("null}");
            }
            else
            {
                this.Value.Write(writer);
                writer.Write(",\"valueType\":\"{0}\"}}", this.ValueTypeName);
            }
        }

        /// <summary>
        /// 将当前对象转换字符串格式
        /// </summary>
        /// <returns>对象的字符串表示形式。</returns>
        public override string ToString()
        {
            using (var writer = new StringWriter())
            {
                this.Write(writer);

                return writer.ToString();
            }
        }
    }
}
